<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" width="640px" :title="`${dialogProps.title}分类`">
    <el-form
      ref="ruleFormRef"
      label-width="150px"
      label-suffix=" :"
      :rules="rules"
      :disabled="dialogProps.isView"
      :model="dialogProps.row"
      :hide-required-asterisk="dialogProps.isView"
    >
      <el-form-item label="菜品分类名称" prop="name">
        <el-input v-model="dialogProps.row!.name" placeholder="请填写" clearable></el-input>
      </el-form-item>
      <el-form-item label="上级分类" prop="parentId">
        <el-select class="w100" v-model="dialogProps.row!.parentId" placeholder="请选择上级分类" clearable>
          <el-option v-for="item in parentCategory" :key="item.name" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机点餐端展示" prop="appletShow">
        <el-radio-group v-model="dialogProps.row!.appletShow" class="ml-4">
          <el-radio :label="1">展示</el-radio>
          <el-radio :label="0">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="菜品分类别名" prop="byName">
        <el-input
          v-model="dialogProps.row!.byName"
          placeholder="设置了别名后，在小票上可以更改为打印分类别名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="分类助记码" prop="helpCode">
        <el-input v-model="dialogProps.row!.helpCode" placeholder="请输入不超过5位数字, 列如123" clearable></el-input>
      </el-form-item>
      <el-form-item label="出品部门" prop="departId">
        <el-select class="w100" v-model="dialogProps.row!.departId" placeholder="请选择出品部门" clearable>
          <el-option v-for="item in departList" :key="item.name" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number class="w100" v-model="dialogProps.row!.sort" :controls="false"></el-input-number>
      </el-form-item>

      <!-- <el-form-item label="分类是否展示图片" prop="sort">
        <el-radio-group>
          <el-radio :value="1" label="是"></el-radio>
          <el-radio :value="0" label="否"></el-radio>
        </el-radio-group>
      </el-form-item> -->
      <!-- <el-form-item prop="选择链接">
        <el-select>
          <el-option></el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item label="选择活动类型" prop="type">
        <el-select v-model="dialogProps.row!.linkType" @change="changeLinkType">
          <el-option v-for="item in linkTypeList" :key="item.value" :label="item.name" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        :label="dialogProps.row!.linkType ===1?  '选择推荐菜品' : dialogProps.row!.linkType === 3 ? '选择充值活动' :''"
        prop="sort"
        v-if="dialogProps.row!.linkType === 1 || dialogProps.row!.linkType === 3"
      >
        <el-input v-model="dialogProps.row!.url" disabled>
          <template #append>
            <div style="line-height: 100%; cursor: pointer" @click="openProductDialog">
              <el-icon size="20"><Search /></el-icon>
            </div>
          </template>
        </el-input>
      </el-form-item>
      <!-- 选中菜品或者充值名称start -->
      <el-form-item
        :label="dialogProps.row!.linkType ===1?  '菜品名称' : dialogProps.row!.linkType === 3 ? '充值活动' :''"
        v-if="dialogProps.row!.linkType === 1 || dialogProps.row!.linkType === 3"
      >
        <el-input v-model="name" disabled />
      </el-form-item>
      <!-- 选中菜品或者充值名称end -->

      <el-form-item label="添加图片" prop="sort">
        <UpLoadImage v-model:imageUrl="dialogProps.row!.upIcon"></UpLoadImage>
      </el-form-item>
      <el-form-item>
        <div style="color: #999999">图片尺寸建议：宽：534px； 高: 170px</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>

  <SelectTreeData @radio="onSelectProduct" ref="selectTreeRef"></SelectTreeData>
  <CouponDialog @on-reset="onReset" @on-confirm="selectCouponList" @on-search="onsearch" ref="couponDialogRef"></CouponDialog>
</template>

<script setup lang="ts" name="CategoryDialog">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Goods, Operation } from "@/api/interface";
import { getDepartMentList } from "@/api/modules/operation";
import { Search } from "@element-plus/icons-vue";
import SelectTreeData from "@/components/SelectTreeData/index.vue";
import { getGoodsList, getFoodCategoryList } from "@/api/modules/goods";
import UpLoadImage from "@/components/Upload/Img.vue";
import { linkTypeList } from "@/utils/serviceDict";
import { getUserDepositRulesList } from "@/api/modules/member";
import CouponDialog from "@/views/marketing/createActivity/components/CouponDialog.vue";

// import { useSelectStore } from "@/stores/modules/dict";

const rules = reactive({
  name: [
    { required: true, message: "菜品分类名称必填" },
    {
      validator: (rules: any, value: any, callback: any) => {
        if (value.length > 7) {
          return callback(new Error("分类名称不能超过8个字符"));
        }
        callback();
      }
    }
  ],
  // byName: [{ required: true, message: "菜品分类别名必填" }],
  // helpCode: [{ required: true, message: "分类助记码必填" }],
  departId: [{ required: true, message: "请选择出品部门" }]
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: Partial<Goods.ResGoodsCategoryList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogVisible = ref(false);
const parentCategory = ref<Goods.ResGoodsCategoryList[]>([]);
const departList = ref<Operation.ResDepartmentList[]>([]);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;
  console.log(params, 445454);

  getFoodCategoryList({ pageNum: 1, pageSize: 9999 }).then(res => {
    res.data.list.push({ id: 0, name: "无上级" });
    parentCategory.value = res.data.list;
  });
  getDepartMentList({ pageNum: 1, pageSize: 9999 }).then(res => {
    // 获取菜品部门
    console.log(res);

    departList.value = res.data.list;
    // console.log(res.data);
    if (params.title === "新增") {
      dialogProps.value.row!.departId = res.data.list[0]?.id;
    }
  });
  // useSelectStore()
  //   .getDic("key_citys")
  //   .then(data => {
  //     parentCategory.value = data;
  //   });
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  // useSelectStore().setDic("key_citys", []);
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!({ upIcon: "", icon: "", ...dialogProps.value.row });
      ElMessage.success({ message: `${dialogProps.value.title}菜品分类成功！` });
      dialogProps.value.getTableList!();
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

// 选择菜品
const selectTreeRef = ref<InstanceType<typeof SelectTreeData> | null>(null);
const couponDialogRef = ref<InstanceType<typeof CouponDialog> | null>(null);
const name = ref("");

const openProductDialog = async (inputParams?: any) => {
  // 判断是否是菜品还是充值活动详细
  if (dialogProps.value.row!.linkType === 1) {
    selectTreeRef.value?.acceptParams({
      title: "选择菜品",
      isView: false,
      selType: "radio",
      mate: "foodSpecId",
      columns: [
        { type: "radio", label: "#", width: 60 },
        { prop: "name", label: "菜品名称", align: "left" },
        { prop: "foodSpecName", label: "量", align: "left" },
        { prop: "foodTypeName", label: "分类", align: "left" }
      ],
      api: getGoodsList,
      treeApi: getFoodCategoryList
    });
  } else if (dialogProps.value.row!.linkType === 3) {
    const { data } = await getUserDepositRulesList({ isAvailable: true, pageNum: 1, pageSize: 999, ...inputParams });
    couponDialogRef.value!.acceptParams({
      title: "充值活动列表(只选一个)",
      search: {
        label: "充值活动名称",
        type: "input"
      },
      tableData: data.list,
      columns: [
        { type: "selection", width: 60 },
        { prop: "name", label: "充值活动名称", width: 200 },
        { prop: "depositTypeText", label: "充值活动类型", width: 150 },
        { prop: "startTime", label: "开始时间" },
        { prop: "endTime", label: "结束时间" }
      ]
    });
  }
};

const onReset = () => {
  dialogProps.value.row!.linkType = 3;
  openProductDialog();
};
const onsearch = (e: any) => {
  dialogProps.value.row!.linkType = 3;
  openProductDialog({ name: e.searchText });
};

// 选择充值活动
const selectCouponList = (e: any) => {
  dialogProps.value.row!.url = "/pages/user/recharge/recharge_detail?id=" + e.tableData[0].id;
  name.value = e.tableData[0].name;
};

interface SelectList {
  index: undefined;
  data: any;
}
// 编辑或者查看时要将数据赋值
const selectList = ref<any>({});
const onSelectProduct = (e: SelectList) => {
  selectList.value = e.data;
  dialogProps.value!.row.url = "/pages/product/product_detail?productId=" + e.data.id;
  name.value = e.data.name;
};

// 切换类型
const changeLinkType = (e: number) => {
  dialogProps.value!.row.url = "";
  name.value = "";
  // recharge/recharge_detail充值活动详情
  // 充值活动
  if (e === 2) {
    dialogProps.value!.row.url = "/pages/user/recharge/recharge";
  }
};

// const onReset = () => {
//   formData.rule.urlType = 3;
//   openProductDialog();
// };
// const selectCouponList = (e: any) => {
//   rechargeUrl.value = "/pages/user/recharge/recharge_detail?id=" + e.tableData[0].id;
//   formData.rule.value = rechargeUrl.value;
//   formData.rule.name = e.tableData[0].name;
// };

// const onsearch = (e: any) => {
//   formData.rule.urlType = 3;
//   openProductDialog({ name: e.searchText });
// };
defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped></style>
